﻿#pragma execution_character_set("utf-8")

#include "audio_dev.h"
#include <QMessageBox>
#include <QDebug>
#define syslog qDebug()

Audio_dev::Audio_dev(QObject *parent) : QObject(parent)
{
    audiodevlist = QAudioDeviceInfo::availableDevices(QAudio::AudioInput);  //获取所有音频输入设备
    cur_dev = audiodevlist.at(0);
    data_dev = new QFile(QCoreApplication::applicationDirPath() + "/temp.raw",this);
    AudioFormat.setSampleRate(8000);    //采样率
    AudioFormat.setChannelCount(1);  //声道数
    AudioFormat.setSampleSize(16);   //位长
    AudioFormat.setCodec("audio/pcm");   //编码格式
    AudioFormat.setByteOrder(QAudioFormat::LittleEndian);
    AudioFormat.setSampleType(QAudioFormat::UnSignedInt);
    if (!cur_dev.isFormatSupported(AudioFormat))
    {
        QMessageBox::critical(0,"音频输入配置测试","测试失败，输入设备不支持该配置");
    }
    else
    {
        audio_dev = new QAudioInput(cur_dev,AudioFormat, this);
        audio_dev->setBufferSize(512);
    }
}

void Audio_dev::start_record()
{
    if(audio_dev == nullptr)
    {
        QMessageBox::warning(0,"","音频输入设备未配置，请选择音频输入设备");
        return;
    }
    if(!data_dev->open(QIODevice::WriteOnly))
    {
        QMessageBox::warning(0,"文件操作","文件打开失败");
        return;
    }
    audio_dev->start(data_dev);
    emit msg_to_ui("开始录音");
}

void Audio_dev::stop_record()
{
    audio_dev->stop();
    data_dev->close();
    emit msg_to_ui("结束录音");
}

QList<QAudioDeviceInfo>& Audio_dev::AvailableAudioDevs()
{
    return audiodevlist;
}
void Audio_dev::dev_change(int index)
{
    cur_dev = audiodevlist.at(index);
    if (!cur_dev.isFormatSupported(AudioFormat))
    {
        QMessageBox::critical(0,"音频输入配置测试","测试失败，输入设备不支持该配置");
        return;
    }
    if(audio_dev == nullptr)
    {
        audio_dev = new QAudioInput(cur_dev,AudioFormat, this);
        audio_dev->setBufferSize(512);
        return;
    }
    delete audio_dev;
    audio_dev = new QAudioInput(cur_dev,AudioFormat, this);
    audio_dev->setBufferSize(512);
}
